import React, { Component } from 'react';
// import { Button, NavBar, Icon } from 'antd-mobile';
import styles from './TempleList.module.scss';
import Axios from '../../utils/request';
import InfiniteScroll from 'react-infinite-scroller';
import { Scrollbars } from 'react-custom-scrollbars';
import Store from '../../redux/Store';
import Action from '../../redux/Action';

class TempleList extends Component {
	constructor(props) {
		super(props);
		this.state = {
			// formattedAddress: '', //当前具体位置
			lnglat: [], //当前位置经纬度
			templeList: [], //寺庙列表
			hasMore: true, //是否加载更多
			pageNum: 1, //加载页数
			pageSize: 10, //每页条数
			total: 1 //数据总量
			// sortOrder: 0 //排序方式  0：智能排序；1：距离排序
		};
	}
	componentDidMount() {
		// console.log('表单框输入内容：', Store.getState().iptValue);
		let _this = this;
		//浏览器精准定位
		window.AMap.plugin('AMap.Geolocation', function() {
			var geolocation = new window.AMap.Geolocation({
				// 是否使用高精度定位，默认：true
				enableHighAccuracy: false,
				// 设置定位超时时间，默认：无穷大
				timeout: 1000,
				// 定位按钮的停靠位置的偏移量，默认：Pixel(10, 20)
				buttonOffset: new window.AMap.Pixel(10, 20)
			});

			geolocation.getCurrentPosition();
			window.AMap.event.addListener(geolocation, 'complete', onComplete);
			window.AMap.event.addListener(geolocation, 'error', onError);

			function onComplete(data) {
				// data是具体的定位信息
				console.log('位置信息：', data);
				let lnglat = _this.state.lnglat;
				lnglat.push(data.position.lng);
				lnglat.push(data.position.lat);
				_this.setState(
					{
						lnglat
					},
					() => {
						//redux管理当前定位城市
						Store.dispatch(Action.citynow(data.addressComponent.city));
					}
				);
			}

			function onError(data) {
				//定位出错
				console.log('定位错误信息', data);
				// if (data.type === 'error') {
					// alert('定位失败');
				// }
				//显示寺庙列表
				Store.dispatch(Action.show('temple'));
			}
		});

		//监听函数
		Store.subscribe(this.listener);
	}
	//获取关键字信息
	listener = () => {
		this.setState(
			{
				templeList: [], //重置寺庙列表为空
				pageNum: 1 //重置页码
			},
			() => {
				this.initData();
			}
		);
	};
	// 获取下一页信息
	getMore = () => {
		if (this.state.total === this.state.templeList.length) {
			return;
		}
		let { pageNum } = this.state;
		this.setState(
			{
				hasMore: false,
				pageNum: pageNum + 1
			},
			() => {
				this.initData();
			}
		);
	};

	//请求寺庙列表
	initData = () => {
		// console.log(Store.getState().keyWord);
		let data = {}; //请求参数
		let url = ''; //请求地址
		//如果请求地址不为空，则条件查询，否则，判断表单输入框是否为空，不为空则条件查询，否则无条件查询
		if (Store.getState().keyWord.length != 0) {
			data = {
				pageIndex: this.state.pageNum, //显示页数
				pageSize: this.state.pageSize, //每页显示条数
				userLocation: this.state.lnglat.join(','), //用户当前位置经纬度
				province: Store.getState().keyWord[0], //省份
				city: Store.getState().keyWord[1] //市
			};
			url = '/temple/getAddress';
		} else if (Store.getState().iptValue != '') {
			data = {
				pageIndex: this.state.pageNum, //显示页数
				pageSize: this.state.pageSize, //每页显示条数
				userLocation: this.state.lnglat.join(','), //用户当前位置经纬度
				search: Store.getState().iptValue //表单查询关键字
			};
			url = '/temple/selectFind';
		} else {
			data = {
				pageIndex: this.state.pageNum, //显示页数
				pageSize: this.state.pageSize, //每页显示条数
				userLocation: this.state.lnglat.join(',') //用户当前位置经纬度
			};
			url = '/temple/getHome';
		}

		Axios({
			method: 'post',
			url: url,
			data: data
		}).then((res) => {
			console.log(res);
			this.setState(
				{
					templeList: this.state.templeList.concat(res.data.data.list),
					total: res.data.data.total,
					hasMore: res.data.data.hasNextPage
				},
				() => {
					console.log(this.state.templeList);
				}
			);
		});
	};
	//关闭关键词
	closeWord = () => {
		console.log('关闭关键词');
	};
	//点击某个寺庙,跳转设备页面
	handleTemple = (templeId) => {
		// console.log(this.props);
		this.props.history.push({ pathname: '/device', state: { templeId } });
	};
	render() {
		const { templeList, total, hasMore } = this.state;
		// console.log('pageNUM', this.state.pageNum);
		// console.log('Store.getState.citynow',Store.getState().show)
		// console.log('Store.getState.sortOrder',Store.getState().sortOrder)
		return (
			<div className={styles.recommend}>
				{/* 寺庙列表为空，没有对应数据 */}
				{templeList.length === 0 ? (
					<div>
						{Store.getState().iptValue === '' ? (
							''
						) : (
							<div className={styles.keyword}>
								<span>当前搜索关键词</span>
								<div className={styles.word}>
									{/* 攀枝花 */}
									{Store.getState().iptValue}
									<img src={require('../../image/chaa@2x.png')} onClick={this.closeWord} />
								</div>
							</div>
						)}
						<div
							className={styles.noList}
							style={Store.getState().iptValue === '' ? { height: '6.24rem' } : { height: '5.77rem' }}
						>
							<img src={require('../../image/lianhua@2x.png')} alt="图片暂未加载" />
							<p>抱歉，暂时还没有符合条件的寺院哦！</p>
						</div>
					</div>
				) : (
					<Scrollbars id="list-scrollbars" style={{ height: 'calc(100vh - 0.43rem)' }} autoHide>
						<InfiniteScroll
							initialLoad={false}
							pageStart={0}
							loadMore={this.getMore}
							hasMore={hasMore}
							useWindow={false}
						>
							{/* 寺庙列表 */}
							<ul className={styles.sList}>
								{templeList.map((item, index) => {
									return (
										<li key={item + index} onClick={() => this.handleTemple(item.templeId)}>
											<div className={styles.boxleft}>
												<img src={item.templeUrl} alt="图片暂不能加载" />
											</div>
											<div className={styles.boxright}>
												<p className={styles.sName}>{item.templeName}</p>
												<p className={styles.sContent}>{item.templeConment}</p>
												<div className={styles.sAddress}>
													<p className={styles.saddress}>{item.templeAddress}</p>
													<p className={styles.skm}>
														<span>距离</span>
														<span className={styles.word}>
															{item.distance !== null ? item.distance / 1000 <= 5 ? (
																item.distance.toFixed(2) + 'm'
															) : (
																(item.distance / 1000).toFixed(2) + 'km'
															) : (
																'暂不能获取'
															)}
														</span>
													</p>
												</div>
											</div>
										</li>
									);
								})}
							</ul>
							{total === templeList.length ? (
								<div style={{ textAlign: 'center', lineHeight: '0.2rem', background: '#fff' }}>
									到底了！
								</div>
							) : (
								''
							)}
						</InfiniteScroll>
					</Scrollbars>
				)}
			</div>
		);
	}
}

export default TempleList;
